package com.pikachu.web.filter;

import com.pikachu.common.annotion.Permission;
import lombok.extern.log4j.Log4j2;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 拦截器
 * @author huang_kangjie
 * @create 2018-08-30 8:49
 **/
@Log4j2
public class AuthInterceptor implements HandlerInterceptor {

     @Override
     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
          String path = request.getRequestURL().toString();

          if ("OPTIONS".equals(request.getMethod())) {
               return true;
          }

          //排除某些请求
          if(path.contains("/xxx/yyy/zzz")) {
               return true;
          }

          String token = request.getHeader("_tk");
          if(StringUtils.isEmpty(token)) {
               //throw new BizException(BaseErrorCodeEnum.NOT_FUND_TOKEN_ERROR);
          }

          Permission permission = ((HandlerMethod) handler).getMethodAnnotation(Permission.class);
          if(permission == null || permission.value().length == 0) {
               //throw new BizException(BaseErrorCodeEnum.NO_PERMISSION_ERROR);
          }

          return true;
     }

     @Override
     public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView modelAndView) throws Exception {

     }

     @Override
     public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

     }

     /**
      * 401
      * @param resp
      * @param errMsg
      * @throws IOException
      */
     public void sendUnAuthResponse(HttpServletResponse resp, String errMsg) throws IOException {
          resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, errMsg);
          resp.getWriter().flush();
     }

     /**
      * 403
      * @param resp
      * @param errMsg
      * @throws IOException
      */
     public void sendForbidenResponse(HttpServletResponse resp, String errMsg) throws IOException {
          resp.sendError(HttpServletResponse.SC_FORBIDDEN, errMsg);
          resp.getWriter().flush();
     }
}
